/**
 * 图片裁剪工具类
 * 用于根据标注区域裁剪图片并生成缩略图
 */

/**
 * 裁剪标注区域图片（包含边距以保留边框和遮罩效果）
 * @param {string} imagePath - 原图路径
 * @param {Object} annotation - 标注对象
 * @param {string} projectPath - 项目路径
 * @param {string} imageId - 图片ID
 * @param {number} thumbnailSize - 缩略图尺寸，默认150px
 * @param {number} paddingRatio - 边距比例，默认0.15（15%）
 * @returns {Promise<string>} - 返回裁剪后图片的文件路径
 */
export async function cropAnnotationImage(imagePath, annotation, projectPath, imageId, thumbnailSize = 150, paddingRatio = 0.15) {
	try {
		// 首先使用electronAPI获取图片数据
		console.log('[ImageCropper] 开始获取图片数据:', imagePath)
		console.log('[ImageCropper] electronAPI可用性:', !!window.electronAPI)
		console.log('[ImageCropper] getLocalImageData可用性:', !!window.electronAPI?.getLocalImageData)
		console.log('[ImageCropper] 标注对象preview:', annotation)
		
		let imageDataUrl = null
		if (window.electronAPI?.getLocalImageData) {
			const result = await window.electronAPI.getLocalImageData(imagePath)
			console.log('[ImageCropper] API调用结果:', result)
			if (result.success) {
				imageDataUrl = result.data
				console.log('[ImageCropper] 图片数据获取成功')
			} else {
				console.error('[ImageCropper] 图片数据获取失败:', result.error)
			}
		} else {
			console.error('[ImageCropper] electronAPI或getLocalImageData不可用')
		}
		
		if (!imageDataUrl) {
			throw new Error('无法获取图片数据')
		}
		
		return new Promise((resolve, reject) => {
			try {
				const img = new Image()
				img.crossOrigin = 'anonymous'
			
			img.onload = () => {
				try {
					console.log('[ImageCropper] 图片加载完成，尺寸:', img.width, 'x', img.height)
					console.log('[ImageCropper] 标注数据:', annotation)
					console.log('[ImageCropper] 标注对象所有属性:', Object.keys(annotation))
					
					const canvas = document.createElement('canvas')
					const ctx = canvas.getContext('2d')
					
					let cropX = 0, cropY = 0, cropWidth = 0, cropHeight = 0
					
					// 根据标注类型计算基础裁剪区域
					if (annotation.type === 'rectangle') {
						// 优先使用标准化后的坐标，其次使用原始坐标
						cropX = annotation.x || annotation.startX || 0
						cropY = annotation.y || annotation.startY || 0
						cropWidth = annotation.width || 0
						cropHeight = annotation.height || 0
						
						console.log('[ImageCropper] 可用坐标信息:', {
							x: annotation.x, y: annotation.y,
							startX: annotation.startX, startY: annotation.startY,
							width: annotation.width, height: annotation.height
						})
						console.log('[ImageCropper] 矩形标注基础区域:', { cropX, cropY, cropWidth, cropHeight })
					} else if (annotation.type === 'line-polygon' && annotation.points && annotation.points.length > 0) {
						// 计算多边形的边界框
						const xs = annotation.points.map(p => p.x)
						const ys = annotation.points.map(p => p.y)
						const minX = Math.min(...xs)
						const maxX = Math.max(...xs)
						const minY = Math.min(...ys)
						const maxY = Math.max(...ys)
						
						cropX = minX
						cropY = minY
						cropWidth = maxX - minX
						cropHeight = maxY - minY
						
						console.log('[ImageCropper] 多边形标注基础区域:', { cropX, cropY, cropWidth, cropHeight })
					} else if (annotation.type === 'point') {
						// 点标注创建小的正方形区域
						const baseSize = 20 // 点标注的基础尺寸
						cropX = (annotation.x || 0) - baseSize / 2
						cropY = (annotation.y || 0) - baseSize / 2
						cropWidth = baseSize
						cropHeight = baseSize
						
						console.log('[ImageCropper] 点标注基础区域:', { cropX, cropY, cropWidth, cropHeight })
					}
					
					// 计算边距：根据标注大小动态调整，但设置最小和最大值
					const minPadding = 10 // 最小边距
					const maxPadding = 50 // 最大边距
					// paddingRatio 通过参数传入，默认15%
					
					// 分别计算水平和垂直边距
					const horizontalPadding = Math.max(minPadding, Math.min(maxPadding, cropWidth * paddingRatio))
					const verticalPadding = Math.max(minPadding, Math.min(maxPadding, cropHeight * paddingRatio))
					
					console.log('[ImageCropper] 计算边距:', { horizontalPadding, verticalPadding, paddingRatio })
					
					// 扩展裁剪区域，添加边距
					const expandedCropX = cropX - horizontalPadding
					const expandedCropY = cropY - verticalPadding
					const expandedCropWidth = cropWidth + (horizontalPadding * 2)
					const expandedCropHeight = cropHeight + (verticalPadding * 2)
					
					console.log('[ImageCropper] 扩展后区域:', { 
						expandedCropX, expandedCropY, expandedCropWidth, expandedCropHeight 
					})
					
					// 确保扩展后的裁剪区域在图片范围内，并转换为整数
					cropX = Math.floor(Math.max(0, Math.min(expandedCropX, img.width)))
					cropY = Math.floor(Math.max(0, Math.min(expandedCropY, img.height)))
					
					// 计算实际可用的宽度和高度
					const maxAvailableWidth = img.width - cropX
					const maxAvailableHeight = img.height - cropY
					cropWidth = Math.ceil(Math.max(1, Math.min(expandedCropWidth, maxAvailableWidth)))
					cropHeight = Math.ceil(Math.max(1, Math.min(expandedCropHeight, maxAvailableHeight)))
					
					// 如果由于边界限制导致裁剪区域过小，尝试向相反方向扩展
					if (expandedCropX < 0) {
						// 左边界超出，向右扩展补偿
						const compensation = Math.abs(expandedCropX)
						cropWidth = Math.min(cropWidth + compensation, img.width - cropX)
					}
					if (expandedCropY < 0) {
						// 上边界超出，向下扩展补偿
						const compensation = Math.abs(expandedCropY)
						cropHeight = Math.min(cropHeight + compensation, img.height - cropY)
					}
					
					// 如果右边界或下边界超出，尝试向左或向上调整起始位置
					if (cropX + cropWidth > img.width) {
						const excess = (cropX + cropWidth) - img.width
						const newCropX = Math.max(0, cropX - excess)
						cropWidth = cropWidth - (cropX - newCropX)
						cropX = newCropX
					}
					if (cropY + cropHeight > img.height) {
						const excess = (cropY + cropHeight) - img.height
						const newCropY = Math.max(0, cropY - excess)
						cropHeight = cropHeight - (cropY - newCropY)
						cropY = newCropY
					}
					
					// 确保最小尺寸
					const minSize = 20
					if (cropWidth < minSize) cropWidth = Math.min(minSize, img.width - cropX)
					if (cropHeight < minSize) cropHeight = Math.min(minSize, img.height - cropY)
					
					console.log('[ImageCropper] 修正后的裁剪区域:', { cropX, cropY, cropWidth, cropHeight })
					console.log('[ImageCropper] 图片尺寸:', { width: img.width, height: img.height })
					
					// 计算缩略图尺寸，保持宽高比
					let thumbWidth, thumbHeight
					const aspectRatio = cropWidth / cropHeight
					
					if (aspectRatio > 1) {
						// 宽大于高
						thumbWidth = thumbnailSize
						thumbHeight = thumbnailSize / aspectRatio
					} else {
						// 高大于宽或正方形
						thumbHeight = thumbnailSize
						thumbWidth = thumbnailSize * aspectRatio
					}
					
					// 确保缩略图尺寸为整数
					thumbWidth = Math.round(thumbWidth)
					thumbHeight = Math.round(thumbHeight)
					
					console.log('[ImageCropper] 缩略图尺寸:', { thumbWidth, thumbHeight, aspectRatio })
					
					// 设置canvas尺寸
					canvas.width = thumbWidth
					canvas.height = thumbHeight
					
					// 设置抗锯齿和图像渲染质量
					ctx.imageSmoothingEnabled = true
					ctx.imageSmoothingQuality = 'high'
					
					// 绘制裁剪后的图片
					ctx.drawImage(
						img,
						cropX, cropY, cropWidth, cropHeight,  // 源图裁剪区域
						0, 0, thumbWidth, thumbHeight         // 目标区域
					)
					
					// 绘制标注效果到canvas上
					drawAnnotationOverlay(ctx, annotation, cropX, cropY, cropWidth, cropHeight, thumbWidth, thumbHeight)
					
					// 转换为base64
					const dataURL = canvas.toDataURL('image/jpeg', 0.8)
					
					// 生成文件名
					const fileName = `${imageId}_${annotation.id}.jpg`
					
					// 保存缩略图文件
					if (window.electronAPI?.saveThumbnail) {
						window.electronAPI.saveThumbnail(projectPath, fileName, dataURL)
							.then(result => {
								if (result.success) {
									console.log('[ImageCropper] 缩略图文件保存成功:', result.filePath)
									resolve(result.filePath) // 返回文件路径而不是base64
								} else {
									console.error('[ImageCropper] 缩略图文件保存失败:', result.error)
									resolve(dataURL) // fallback到base64
								}
							})
							.catch(error => {
								console.error('[ImageCropper] 缩略图保存异常:', error)
								resolve(dataURL) // fallback到base64
							})
					} else {
						console.warn('[ImageCropper] saveThumbnail API不可用，使用base64')
						resolve(dataURL)
					}
					
				} catch (error) {
					console.error('[ImageCropper] 裁剪处理失败:', error)
					reject(error)
				}
			}
			
			img.onerror = (error) => {
				console.error('[ImageCropper] 图片加载失败:', error)
				reject(new Error('图片加载失败'))
			}
			
			// 使用获取到的图片数据
			console.log('[ImageCropper] 加载图片数据')
			img.src = imageDataUrl
			
			} catch (error) {
				console.error('[ImageCropper] 初始化失败:', error)
				reject(error)
			}
		})
	} catch (error) {
		console.error('[ImageCropper] 外层错误:', error)
		throw error
	}
}

/**
 * 生成标注ID的缩略图文件名
 * @param {string} annotationId - 标注ID
 * @param {string} imageId - 图片ID
 * @returns {string} - 缩略图文件名
 */
export function generateThumbnailFileName(annotationId, imageId) {
	return `thumb_${imageId}_${annotationId}.jpg`
}

/**
 * 批量生成标注缩略图
 * @param {string} imagePath - 原图路径
 * @param {Array} annotations - 标注数组
 * @param {string} projectPath - 项目路径
 * @param {string} imageId - 图片ID
 * @param {number} thumbnailSize - 缩略图尺寸，默认150px
 * @param {number} paddingRatio - 边距比例，默认0.15（15%）
 * @returns {Promise<Array>} - 返回包含缩略图数据的标注数组
 */
export async function batchCropAnnotations(imagePath, annotations, projectPath, imageId, thumbnailSize = 150, paddingRatio = 0.15) {
	const results = []
	
	for (const annotation of annotations) {
		try {
			const thumbnailData = await cropAnnotationImage(imagePath, annotation, projectPath, imageId, thumbnailSize, paddingRatio)
			results.push({
				...annotation,
				thumbnailData
			})
		} catch (error) {
			console.error(`[ImageCropper] 批量裁剪失败，标注ID: ${annotation.id}`, error)
			results.push({
				...annotation,
				thumbnailData: null
			})
		}
	}
	
	return results
}

/**
 * 将十六进制颜色转换为rgba
 * @param {string} hex - 十六进制颜色  
 * @param {number} alpha - 透明度 (0-1)
 * @returns {string} rgba颜色字符串
 */
function hexToRgba(hex, alpha = 0.2) {
	if (!hex || !hex.startsWith('#')) return `rgba(0, 0, 0, ${alpha})`
	const r = parseInt(hex.slice(1, 3), 16)
	const g = parseInt(hex.slice(3, 5), 16)
	const b = parseInt(hex.slice(5, 7), 16)
	return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

/**
 * 在canvas上绘制标注覆盖层（边框、填充、遮罩等）
 * @param {CanvasRenderingContext2D} ctx - Canvas绘图上下文
 * @param {Object} annotation - 标注对象
 * @param {number} cropX - 裁剪区域X坐标
 * @param {number} cropY - 裁剪区域Y坐标
 * @param {number} cropWidth - 裁剪区域宽度
 * @param {number} cropHeight - 裁剪区域高度
 * @param {number} canvasWidth - Canvas宽度
 * @param {number} canvasHeight - Canvas高度
 */
function drawAnnotationOverlay(ctx, annotation, cropX, cropY, cropWidth, cropHeight, canvasWidth, canvasHeight) {
	if (!annotation || !ctx) return
	
	// 计算坐标转换比例
	const scaleX = canvasWidth / cropWidth
	const scaleY = canvasHeight / cropHeight
	
	// 获取标注颜色，默认为蓝色
	const color = annotation.color || '#409EFF'
	const lineWidth = 2
	
	console.log('[ImageCropper] 绘制标注覆盖层:', {
		type: annotation.type,
		color,
		cropArea: { cropX, cropY, cropWidth, cropHeight },
		canvasSize: { canvasWidth, canvasHeight },
		scale: { scaleX, scaleY }
	})
	
	// 保存当前canvas状态
	ctx.save()
	
	try {
		if (annotation.type === 'rectangle') {
			drawRectangleOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth)
		} else if (annotation.type === 'line-polygon') {
			drawPolygonOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth)
		} else if (annotation.type === 'point') {
			drawPointOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth)
		}
	} catch (error) {
		console.error('[ImageCropper] 绘制标注覆盖层失败:', error)
	}
	
	// 恢复canvas状态
	ctx.restore()
}

/**
 * 绘制矩形标注覆盖层
 */
function drawRectangleOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth) {
	const rectX = (annotation.x - cropX) * scaleX
	const rectY = (annotation.y - cropY) * scaleY
	const rectWidth = annotation.width * scaleX
	const rectHeight = annotation.height * scaleY
	
	console.log('[ImageCropper] 绘制矩形:', { rectX, rectY, rectWidth, rectHeight })
	
	// 绘制填充
	ctx.fillStyle = hexToRgba(color, 0.2)
	ctx.fillRect(rectX, rectY, rectWidth, rectHeight)
	
	// 绘制边框
	ctx.strokeStyle = color
	ctx.lineWidth = lineWidth
	ctx.strokeRect(rectX, rectY, rectWidth, rectHeight)
}

/**
 * 绘制多边形标注覆盖层
 */
function drawPolygonOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth) {
	if (!annotation.points || annotation.points.length < 3) return
	
	console.log('[ImageCropper] 绘制多边形，点数:', annotation.points.length)
	
	ctx.beginPath()
	
	// 转换第一个点并移动到起始位置
	const firstPoint = annotation.points[0]
	const startX = (firstPoint.x - cropX) * scaleX
	const startY = (firstPoint.y - cropY) * scaleY
	ctx.moveTo(startX, startY)
	
	// 绘制其余点
	for (let i = 1; i < annotation.points.length; i++) {
		const point = annotation.points[i]
		const x = (point.x - cropX) * scaleX
		const y = (point.y - cropY) * scaleY
		ctx.lineTo(x, y)
	}
	
	// 闭合路径
	ctx.closePath()
	
	// 绘制填充
	ctx.fillStyle = hexToRgba(color, 0.2)
	ctx.fill()
	
	// 绘制边框
	ctx.strokeStyle = color
	ctx.lineWidth = lineWidth
	ctx.stroke()
}

/**
 * 绘制点标注覆盖层
 */
function drawPointOverlay(ctx, annotation, cropX, cropY, scaleX, scaleY, color, lineWidth) {
	const pointX = (annotation.x - cropX) * scaleX
	const pointY = (annotation.y - cropY) * scaleY
	const radius = 5 // 点的半径
	
	console.log('[ImageCropper] 绘制点标注:', { pointX, pointY })
	
	// 绘制点的填充圆
	ctx.beginPath()
	ctx.arc(pointX, pointY, radius, 0, Math.PI * 2)
	ctx.fillStyle = color
	ctx.fill()
	
	// 绘制点的边框
	ctx.strokeStyle = '#ffffff'
	ctx.lineWidth = lineWidth
	ctx.stroke()
}